import React from 'react';
import { isInIcestark } from '@ice/stark-app';
import { store } from '@ice/stark-data';
import { hcpConfirm } from '@/components';

const hcpWarningModal = (e) => {
    hcpConfirm({
        title: '提示',
        content: (
            <div className="main-content">
                <span className="iconfont iconfont-yellow icon-confirm-warning" />
                <span className="main-content-info">您尚未开通此功能的操作权限，如需操作，请联系管理员申请</span>
            </div>
        ),
        cancelText: null,
        okText: '知道了',
        onFinish: () => {},
    });
};

const isAuthorized = (authority) => {
    if (!authority || !isInIcestark()) return { isPermission: true };

    let isPermission = true;

    const getAuths = (store.get('BTN_AUTH') || []).map((item) => item.permission); // 从框架获取按钮权限集合

    if (typeof authority === 'string') {
        // 单个权限词条
        if (getAuths.indexOf(authority) === -1) {
            isPermission = false;
        }
    } else if (authority instanceof Array && authority.length > 0) {
        // 多个权限词条
        authority.forEach((item) => {
            if (getAuths.indexOf(item) === -1) {
                isPermission = false;
            }
        });
    }
    return { isPermission, hcpWarningModal };
};

const Authorized = ({ authority, noMatch, children }) => {
    if (!authority || !isInIcestark()) return children;

    let isPermission = true;

    const getAuths = (store.get('BTN_AUTH') || []).map((item) => item.permission); // 从框架获取按钮权限集合
    if (typeof authority === 'string') {
        // 单个权限词条
        if (getAuths.indexOf(authority) === -1) {
            isPermission = false;
        }
    } else if (authority instanceof Array && authority.length > 0) {
        // 多个权限词条
        authority.forEach((item) => {
            if (getAuths.indexOf(item) === -1) {
                isPermission = false;
            }
        });
    }

    return isPermission ? children : <span onClick={hcpWarningModal}>{noMatch}</span>;
};

export { isAuthorized };

export default Authorized;
